package shunfeng_interface

import (
	"errors"
	"strconv"
)

// CheckTaskNo 检测该taskNo是否存在
func (s *Serve) CheckTaskNo(taskNo string) (isExist bool, err error) {
	row := s.db.QueryRow("SELECT count(*) from task WHERE taskNo = ?", taskNo)

	var count int
	err = row.Scan(&count)
	if err != nil {
		return false, err
	}
	if count > 0 {
		return true, nil
	} else {
		return false, nil
	}
}

// InsertTask 插入任务数据
func (s *Serve) InsertTask(req StartRequetStruct) (int64, error) {
	result, err := s.db.Exec("INSERT INTO task VALUES (NULL,?,?,?,?,?)", req.TransitDepotNo, req.TaskNo, req.CrateNo, "Start", "Null")
	if result == nil {
		return 0, errors.New("数据库result为空错误")
	} else if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

// GetWorkState 获取任务的工作状态
func (s *Serve) GetWorkState(taskNo string) (workState string, err error) {
	row := s.db.QueryRow("SELECT workState from task WHERE taskNo = ?", taskNo)

	err = row.Scan(&workState)
	return workState, err
}

func (s *Serve) SetTaskState(taskNo, state string) error {
	_, err := s.db.Exec("UPDATE task SET taskState = ? WHERE taskNo = ?", state, taskNo)
	return err
}

func (s *Serve) GetRecordByTaskNo(taskNo string) (obj StopObj, err error) {
	row := s.db.QueryRow("SELECT actualLength,actualWidth,actualHeight,pic1,pic2,pic3,pic4,videoPath "+
		"FROM record WHERE taskNo = ?", taskNo)
	var pic1, pic2, pic3, pic4 string

	err = row.Scan(&obj.ActualLength, &obj.ActualWidth, &obj.ActualHeight, &pic1, &pic2, &pic3, &pic4, &obj.VideoPath)
	picUrl := "http://" + s.ip + ":" + strconv.Itoa(s.port) + "/images/"
	obj.PicUrls = append(obj.PicUrls, picUrl+pic1)
	obj.PicUrls = append(obj.PicUrls, picUrl+pic2)
	obj.PicUrls = append(obj.PicUrls, picUrl+pic3)
	obj.PicUrls = append(obj.PicUrls, picUrl+pic4)

	obj.VideoPath = "http://" + s.ip + ":" + strconv.Itoa(s.port) + "/videos/" + obj.VideoPath
	return obj, err
}
